package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.plaf.PanelUI;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpServletRequest request;

    //登录
    @PostMapping("/login")
    public R login(@RequestBody Employee employee){
        R r  = employeeService.login(employee);
        if (r.getCode()==1){
            HttpSession session = request.getSession();
            session.setAttribute("employee",((Employee)r.getData()).getId());
        }
        return r;
    }

    //退出
    @PostMapping("/logout")
    public R logout(){
        HttpSession session = request.getSession();
        session.invalidate();

        return R.success("退出成功");
    }


    //添加员工
    @PostMapping
    public R add(@RequestBody Employee employee){
        //判断参数
        if (employee == null){
            return R.error("参数异常");
        }
        //1.补全参数
        //1.1补全密码
        //1.2 加密密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //4.调用service进行储存
        employeeService.save(employee);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R findPage(Integer page,Integer pageSize,String name){
//        int i=1/0;
        R r = employeeService.findPage(page,pageSize,name);
        return  r;
    }
    //修改状态和数据
    @PutMapping
    public R updateStatus(@RequestBody Employee employee){
        R r  = employeeService.updateStatus(employee);
        return r;
    }
    //修改回显
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
